package com.ssmdemo.aop.imp;



import com.ssmdemo.aop.bean.LoginUser;
import com.ssmdemo.constant.LoginConstant;
import com.ssmdemo.pojo.User;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.lang.reflect.Field;
import java.util.Arrays;


@Aspect     //aop
@Component
public class LoginUserAop{


    @Autowired
    HttpSession session;

//    @Before("@annotation(loginUser)")
    @Around("@annotation(loginUser)")
    public void handler(ProceedingJoinPoint joinPoint, LoginUser loginUser){

        System.out.println("启动aop前置-在方法运行前启动");

        User user=(User) session.getAttribute(LoginConstant.SUCCESS_USER);
        Object[] arg=joinPoint.getArgs();

        System.out.println("session"+user.toString());
        System.out.println("1234"+Arrays.toString(arg));


        //查看放入哪里（Emp或User）
        if (loginUser.saveParamObject()){

            //获取Controller形参(Emp)
            for (int i=0;i<arg.length;i++){
                Object param=arg[i];

                //获取属性
                Field[] fields=param.getClass().getDeclaredFields();


                for (int j=0;j<fields.length;j++){

                    Field field=fields[j];

                    //找到属性类型是 User的
                    if (field.getType()==User.class){
                        field.setAccessible(true);
                        try {
                            field.set(param,user);//把当前用户 user写入到形参的 user类型属性里面呢
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

        }else{
            for (int i=0;i<arg.length;i++){
                if (arg[i].getClass()==User.class){
                    //反射方式拷贝
                    //user-->arg[i]
//                    BeanUtils.copyProperties(user,arg[i]);
                    arg[i]=user;
                }
            }
        }
        try {
            joinPoint.proceed(arg);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }

}
